/**
 *
 * 通过此脚本 node scripts/init.mjs
 * 可以自动获取用于生成api的生成脚本代码:
 * /scripts/temp/a.mjs
 * /scripts/temp/b.mjs
 * /scripts/temp/c.mjs
 *
 * 以及用于请求的fetch工具类函数：
 * /src/api/http.ts
 *
 */
import fs from 'fs'
import https from 'https'
import URL from 'url'

// 配置
const projectId = 6938943 // apiFox 项目id
const API_PREFIX = '/pet/admin' // 接口前缀
const filter = `export const filter = (i) => {return i.path}`

if (!fs.existsSync('./scripts/temp/')) {
	fs.mkdirSync('./scripts/temp/')
}

const gitUrl = 'https://gitcode.net/jsoncode/api-fox-auto-build/-/raw/master/'
console.log('获取a.mjs')
let a = await get('a.txt')
console.log('a===',a)
a = a.replace('1234567', projectId.toString())
a = a.replace(`VITE_APP_API_PREFIX  = '/api'`, `VITE_APP_API_PREFIX  = '${API_PREFIX}'`)
a = a.replace(`export const filter = (i) => {return i.path}`, filter)
fs.writeFileSync('./scripts/temp/a.mjs', a, {encoding: 'utf-8'})

console.log('获取b.mjs')
const b = await get('b.txt')
fs.writeFileSync('./scripts/temp/b.mjs', b, {encoding: 'utf-8'})

console.log('获取c.mjs')
const c = await get('c.txt')
fs.writeFileSync('./scripts/temp/c.mjs', c, {encoding: 'utf-8'})

console.log('获取http.ts')
const d = await get('d.txt')
fs.writeFileSync('./scripts/temp/http.ts.txt', d, {encoding: 'utf-8'})

console.log('获取http.ts')
const e = await get('e.txt')
fs.writeFileSync('./scripts/temp/vite.config.ts.txt', e, {encoding: 'utf-8'})

/**
 * 修改ignore文件,向其中添加以下三个匹配值
 *
 * scripts/api*.json
 * scripts/token
 * scripts/data.json
 */
let igFile = fs.existsSync('./.gitignore') ? fs.readFileSync('./.gitignore', {encoding: 'utf-8'}) : ''
if (igFile) {
	let igList = igFile.split(/\n/)
	let willPush = [
		'scripts/temp/*.txt',
		'scripts/temp/*-old.json',
		'scripts/temp/data.json',
		'scripts/token',
	]
	if (!igList.includes(willPush[0])) {
		igList = igList.concat(willPush)
		igFile = igList.join('\n')
		fs.writeFileSync('./.gitignore', igFile, {encoding: 'utf-8'})
	}
}
/**
 * 添加启动脚本
 *
 * 向package.json中添加 yarn api启动命令
 */
let pgFile = fs.existsSync('./package.json') ? fs.readFileSync('./package.json', {encoding: 'utf-8'}) : ''
if (pgFile) {

	if (!pgFile.includes(`"api": "node scripts/temp/c.mjs"`)) {
		pgFile = pgFile.replace(/([^\n\S]+)("scripts":\s*\{)/, '$1$2\n$1$1"api": "node scripts/temp/c.mjs",')
		fs.writeFileSync('./package.json', pgFile, {encoding: 'utf-8'})
	}
}

export async function get(name) {
	const url = gitUrl + name
	const urlObj = URL.parse(url)
	return new Promise((resolve) => {
		const req = https.request(
			{
				...urlObj,
				rejectUnauthorized: false,
				method: 'GET', // 请求方式
				headers: {
					'Content-type': 'application/x-www-form-urlencoded', // 编码格式
					referer: url, // 如果资源有防盗链，则清空该属性
				},
			},
			(res) => {
				if (res.statusCode === 200) {
					res.setEncoding('utf-8')
					let data = ''
					res.on('data', (chunk) => {
						data += chunk
					})
					res.on('end', () => {
						resolve(data)
					})
				} else {
					resolve(null)
				}
			},
		)
		req.on('error', (e) => {
			console.log('error', e.toString())
			resolve(null)
		})
		req.end()
	})
}
